package edu.uwosh.cs342.group2.project4;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location; 
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import edu.uwosh.cs342.group2.project4.database.*;
import edu.uwosh.cs342.group2.project4.storage.*;

public class MainMenuActivity extends MapActivity {
	Button favs;
	ListView favList;
	ArrayList<String> favorites;
	MapView mapView;
	LocationManager locationManager;
	double latitude;
	double longitude;
	MapController mc;
	Coordinates c;
	ThreadedDbHelper db;
	List<Overlay> listOfOverlays;
	Geocoder gc;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	  db = new ThreadedDbHelper(MainMenuActivity.this);
		
		favorites = new ArrayList<String>();
		
		
		
	
	Criteria criteria = new Criteria(); 
	criteria.setAccuracy(Criteria.ACCURACY_FINE); // fine location data
	criteria.setBearingRequired(true); // need bearing to rotate map
		criteria.setCostAllowed(true); // OK to incur monetary cost
		criteria.setPowerRequirement(Criteria.POWER_LOW); // try to conserve
		criteria.setAltitudeRequired(false); // don't need altitude data
		// get the LocationManager
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		String provider = locationManager.getBestProvider(criteria, true);
		Location location = locationManager.getLastKnownLocation(provider); 
		
		
		Button favs = (Button) findViewById(R.id.btnFavs);
		
		List<Category> categories = db.GetAllCategories();

		for (Category t : categories) {
			favorites.add(t.getName());
		}
		mapView = (MapView) findViewById(R.id.mapView);
		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
		
		mapView.setBuiltInZoomControls(true);
		
		mapView.displayZoomControls(true);

		MapController mc = mapView.getController();
	
		mc.setZoom(13);
		updateLocation(location); 

		

		locationManager.requestLocationUpdates(provider, 0, 0,locationListener);
		
		mapView.invalidate();

		favs.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				List<Category> categories = db.GetAllCategories();
				favorites = new ArrayList<String>();
				for (Category t : categories) {
					favorites.add(t.getName());
				}
				final Dialog listDialog = new Dialog(MainMenuActivity.this);
				listDialog.setTitle("Favorites");
				LayoutInflater li = (LayoutInflater) MainMenuActivity.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View v = li.inflate(R.layout.fav, null, false);
				listDialog.setContentView(v);
				listDialog.setCancelable(true);

				ListView list1 = (ListView) listDialog
						.findViewById(R.id.favList);

				list1.setAdapter(new ArrayAdapter<String>(
						MainMenuActivity.this, R.layout.list_item, favorites));

				list1.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						List<edu.uwosh.cs342.group2.project4.storage.Location> loc = db.GetAllLocations();
						listOfOverlays = mapView.getOverlays();
						listOfOverlays.clear();
						
						ArrayList<edu.uwosh.cs342.group2.project4.storage.Location> favs = new ArrayList<edu.uwosh.cs342.group2.project4.storage.Location>();
						
						
						for(edu.uwosh.cs342.group2.project4.storage.Location lo: loc){
							   String[] a =  lo.getDescription().split(" ");
							   if(a[0].equals(favorites.get(position))){
								favs.add(lo);
							    MapOverlay m = new MapOverlay(lo.getCoordinates().getCords(), getApplicationContext(), (Places)getApplicationContext());
								    listOfOverlays.add(m);
							   }
							
						}
						
						Places mApp = (Places)getApplicationContext();
						mApp.setArray(favs);
				
						listDialog.dismiss();

					}

				});
				listDialog.show();
			}

		});
	}
	
	private void animate()
	{
		mc = mapView.getController();
		c = new Coordinates(latitude, longitude);
		mc.animateTo(c.getCords());
		mc.setZoom(13);
	}

	private void updateLocation(Location location) {
		if (location !=null)
		{
			// get the latitude and longitude
			latitude = location.getLatitude();
			longitude = location.getLongitude();
			animate();
		}
		
	}

	private final LocationListener locationListener = new LocationListener() 
	{
			// when the location is changed
		    public void onLocationChanged(Location location) 
			{
				updateLocation(location);
			}

			public void onProviderDisabled(String arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onProviderEnabled(String arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				// TODO Auto-generated method stub
				
			}
	}; // end locationListener

 public void onResume() {
	
	 super.onResume();
	 
	 
	
	 }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.layerMenu:
			this.setLayers(getCurrentFocus());
			break;
		
		case R.id.searchByCoords:
			this.searchCoords(getCurrentFocus());
			break;
			
		case R.id.search:
			this.search(getCurrentFocus());
			break;
		}
		return true;
	}
	
	public void search(View view)
	{
		final Dialog searchDialog = new Dialog(MainMenuActivity.this);
		searchDialog.setTitle("Search By Coordinates");
		LayoutInflater li = (LayoutInflater) MainMenuActivity.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		gc = new Geocoder(this, Locale.US);
		
		View newView = li.inflate(R.layout.namedsearch, null, false);
		
		searchDialog.setContentView(newView);
		searchDialog.setCancelable(true);
		
		searchDialog.show();
		
		
		final EditText name = (EditText) searchDialog.findViewById(R.id.editName);
	    Button searchButton = (Button) searchDialog.findViewById(R.id.searchButton);
	    Button cancelButton = (Button) searchDialog.findViewById(R.id.cancelButton);
////	    
	    searchButton.setOnClickListener(new View.OnClickListener() {
	    	   public void onClick(View v) {
	    		   //Gets their answer
	    		    String searchName = name.getText().toString();
	    		    
	    		    
	    		    
	    		    try {
	    		        List<Address> geoResults = gc.getFromLocationName(searchName, 1);
	    		        while (geoResults.size()==0) {
	    		            geoResults = gc.getFromLocationName(searchName, 1);
	    	   				Toast.makeText(getApplicationContext(), "While", Toast.LENGTH_SHORT).show();
	    		        }
	    		        if (geoResults.size()>0) {
	    		            Address addr = geoResults.get(0);
	    		            latitude = addr.getLatitude();
	    		            longitude = addr.getLongitude();
	    		            

	    	   				Toast.makeText(getApplicationContext(), "Longitude: " + longitude + "  Latitude: " + latitude, Toast.LENGTH_SHORT).show();
	    		        }
	    		    } catch (Exception e) {
	    		        System.out.print(e.getMessage());

    	   				Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
	    		    }
	    		    
	    		    
	   				searchDialog.dismiss();
	   				
	   			  ArrayList<edu.uwosh.cs342.group2.project4.storage.Location> goodshit = db.SearchPlaces(new Coordinates(latitude,longitude ), 500, false, null);
	   			Places mApp = (Places)getApplicationContext();
	   			mApp.setArray(goodshit);
	   			

	   			listOfOverlays = mapView.getOverlays();
	   			listOfOverlays.clear();
	   			for(edu.uwosh.cs342.group2.project4.storage.Location l: goodshit){
	   		    MapOverlay m = new MapOverlay(l.getCoordinates().getCords(), getApplicationContext(), (Places)getApplicationContext());
	   			    listOfOverlays.add(m);
	   			}
	   				
	   				animate();
	    	   }
			});
	    
	  
		
	    
	    cancelButton.setOnClickListener(new View.OnClickListener() {
	    	   public void onClick(View v) {
	   				searchDialog.dismiss();
	    	   }
			});
	    
		
		
	}

	public void searchCoords(View view)
	{
		final Dialog searchDialog = new Dialog(MainMenuActivity.this);
		searchDialog.setTitle("Search By Coordinates");
		LayoutInflater li = (LayoutInflater) MainMenuActivity.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		View newView = li.inflate(R.layout.search, null, false);
		
		searchDialog.setContentView(newView);
		searchDialog.setCancelable(true);
		
		searchDialog.show();
		


		final EditText lat = (EditText) searchDialog.findViewById(R.id.editLat);
		final EditText longi = (EditText) searchDialog.findViewById(R.id.editLong);
	    Button searchButton = (Button) searchDialog.findViewById(R.id.searchButton);
	    Button cancelButton = (Button) searchDialog.findViewById(R.id.cancelButton);
////	    
	    searchButton.setOnClickListener(new View.OnClickListener() {
	    	   public void onClick(View v) {
	    		   //Gets their answer
	    		    double newLong = Double.parseDouble(longi.getText().toString());
	    		    double newLat = Double.parseDouble(lat.getText().toString());
	    		    
	    		    longitude = newLong;
	    		    latitude = newLat;
	    		   
	   				Toast.makeText(getApplicationContext(), "Longitude: " + longitude + "  Latitude: " + latitude, Toast.LENGTH_SHORT).show();
	   				
	   				searchDialog.dismiss();
	   				
	   				animate();
	    	   }
			});
	    
	    cancelButton.setOnClickListener(new View.OnClickListener() {
	    	   public void onClick(View v) {
	   				searchDialog.dismiss();
	    	   }
			});
	    
		
		
		
	}
	public void setLayers(View view) {

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Layers");
		alert.setMessage("Choose desired layer");

		// alert.setContentView(R.layout.layers);

		alert.setPositiveButton("Satelite",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						mapView.setSatellite(true);
					}
				});

		alert.setNegativeButton("Street",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						mapView.setSatellite(false);
					}
				});
		alert.show();
	}
	public static void saveLocation(Context c){
	  System.out.println(c.toString())  ;

	}
}
